#include "pinyin_com.h"
#include <ctype.h>
#include <string.h>

// 初始化输入法上下文
void init_input_context(InputContext *ctx) {
    memset(ctx, 0, sizeof(InputContext));
    ctx->mode = MODE_ENGLISH;
    ctx->layout = LAYOUT_LETTERS;
}

// 更新候选词按钮显示
static void update_candidate_buttons(InputContext *ctx) {
    int start = ctx->current_page * CANDIDATES_PER_PAGE;
    int end = start + CANDIDATES_PER_PAGE;
    
    if (end > ctx->candidate_count) {
        end = ctx->candidate_count;
    }
    
    // 更新页码显示
    char page_text[32];
    snprintf(page_text, sizeof(page_text), "第%d/%d页", 
             ctx->current_page + 1, ctx->total_pages);
    gtk_label_set_text(GTK_LABEL(ctx->page_label), page_text);

    // 获取候选词区域的宽度
    GtkAllocation alloc;
    gtk_widget_get_allocation(ctx->candidate_box, &alloc);
    int box_width = alloc.width;

    // 计算每个按钮的精确宽度，确保10个按钮能在一行显示
    // 预留20px作为按钮之间的间距
    int button_width = (box_width - 20) / 20;
    if (button_width < 30) {
        button_width = 30; // 设置最小宽度
    }

    // 强制设置每行显示10个按钮
    gtk_flow_box_set_max_children_per_line(GTK_FLOW_BOX(ctx->candidate_box), 10);
    gtk_flow_box_set_homogeneous(GTK_FLOW_BOX(ctx->candidate_box), TRUE); // 使所有按钮大小一致

    // 更新候选词按钮
    for (int i = 0; i < CANDIDATES_PER_PAGE; i++) {
        int index = start + i;
        if (index < end) {
            char button_text[16];
            snprintf(button_text, sizeof(button_text), "%d.%s", i + 1, ctx->candidates[index]);
            gtk_button_set_label(GTK_BUTTON(ctx->candidate_buttons[i]), button_text);

            // 设置按钮宽度（同时设置最小和自然宽度）
            gtk_widget_set_size_request(ctx->candidate_buttons[i], button_width, 30);
            gtk_widget_set_hexpand(ctx->candidate_buttons[i], FALSE); // 禁止水平扩展

            gtk_widget_show(ctx->candidate_buttons[i]);
        } else {
            gtk_widget_hide(ctx->candidate_buttons[i]);
        }
    }
    
    // 强制重排容器
    gtk_widget_queue_resize(ctx->candidate_box);
}

// 查找匹配的候选词
static void find_candidates(InputContext *ctx) {
    ctx->candidate_count = 0;
    ctx->current_page = 0;
    
    if (ctx->pinyin_len == 0) {
        gtk_label_set_text(GTK_LABEL(ctx->pinyin_label), "拼音: ");
        return;
    }
    
    // 遍历拼音映射表查找匹配项
    for (int i = 0; i < pinyin_map_size; i++) {
        if (strncmp(ctx->pinyin_buffer, pinyin_map[i].pinyin, ctx->pinyin_len) == 0) {
            ctx->candidate_count = pinyin_map[i].count;
            memcpy(ctx->candidates, pinyin_map[i].hanzi, 
                  sizeof(char[4]) * ctx->candidate_count);
            
            ctx->total_pages = (ctx->candidate_count + CANDIDATES_PER_PAGE - 1) / CANDIDATES_PER_PAGE;
            
            char pinyin_text[128];
            snprintf(pinyin_text, sizeof(pinyin_text), "拼音: %s", ctx->pinyin_buffer);
            gtk_label_set_text(GTK_LABEL(ctx->pinyin_label), pinyin_text);
            break;
        }
    }
    
    update_candidate_buttons(ctx);
}

// 向文本缓冲区添加内容
static void add_to_buffer(InputContext *ctx, const char *str) {
    int len = strlen(str);
    if (ctx->text_len + len >= (int)sizeof(ctx->text_buffer)) {
        return; // 缓冲区已满
    }
    
    // 移动光标后的文本为新内容腾出空间
    memmove(ctx->text_buffer + ctx->cursor_pos + len, 
            ctx->text_buffer + ctx->cursor_pos, 
            ctx->text_len - ctx->cursor_pos + 1);
    
    // 插入新内容
    memcpy(ctx->text_buffer + ctx->cursor_pos, str, len);
    ctx->text_len += len;
    ctx->cursor_pos += len;
    gtk_entry_set_text(GTK_ENTRY(ctx->entry), ctx->text_buffer);
}

// 候选词选择回调
static void on_candidate_selected(GtkWidget *widget, gpointer data) {
    InputContext *ctx = (InputContext *)data;
    int index = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "index")) + 
                ctx->current_page * CANDIDATES_PER_PAGE;
    
    if (index < ctx->candidate_count) {
        add_to_buffer(ctx, ctx->candidates[index]);
        ctx->pinyin_buffer[0] = '\0';
        ctx->pinyin_len = 0;
        ctx->candidate_count = 0;
        gtk_label_set_text(GTK_LABEL(ctx->pinyin_label), "拼音: ");
        update_candidate_buttons(ctx);
    }
}

// 更新模式按钮显示
static void update_mode_button(InputContext *ctx) {
    GtkStyleContext *context = gtk_widget_get_style_context(ctx->mode_button);
    
    if (ctx->mode == MODE_CHINESE) {
        gtk_style_context_add_class(context, "active-mode");
        gtk_style_context_remove_class(context, "english-mode");
    } else {
        gtk_style_context_add_class(context, "english-mode");
        gtk_style_context_remove_class(context, "active-mode");
    }
}

// 更新布局按钮显示
static void update_layout_button(InputContext *ctx) {
    switch (ctx->layout) {
        case LAYOUT_LETTERS:
            // 在字母布局中显示"?123"
            gtk_button_set_label(GTK_BUTTON(ctx->layout_button), "?123");
            break;
        case LAYOUT_NUMBERS:
            // 在数字布局中显示"ABC"
            gtk_button_set_label(GTK_BUTTON(ctx->layout_button), "ABC");
            break;
        case LAYOUT_SYMBOLS:
            // 在符号布局中显示"123"
            gtk_button_set_label(GTK_BUTTON(ctx->layout_button), "123");
            break;
    }
}

// 键盘按钮点击回调
static void on_keyboard_button_clicked(GtkWidget *widget, gpointer data) {
    InputContext *ctx = (InputContext *)data;
    const char *label = gtk_button_get_label(GTK_BUTTON(widget));
    
    if (strcmp(label, "←") == 0) {
        // 处理退格键
        if (ctx->pinyin_len > 0) {
            // 拼音模式下删除拼音字符
            ctx->pinyin_buffer[--ctx->pinyin_len] = '\0';
            find_candidates(ctx);
        } else if (ctx->cursor_pos > 0) {
            // 文本模式下删除字符
            memmove(ctx->text_buffer + ctx->cursor_pos - 1, 
                    ctx->text_buffer + ctx->cursor_pos, 
                    ctx->text_len - ctx->cursor_pos + 1);
            ctx->text_len--;
            ctx->cursor_pos--;
            gtk_entry_set_text(GTK_ENTRY(ctx->entry), ctx->text_buffer);
        }
    } else if (strcmp(label, "空格") == 0) {
        // 处理空格键
        if (ctx->mode == MODE_CHINESE && ctx->candidate_count > 0) {
            // 中文模式下选择第一个候选词
            add_to_buffer(ctx, ctx->candidates[0]);
            ctx->pinyin_buffer[0] = '\0';
            ctx->pinyin_len = 0;
            ctx->candidate_count = 0;
            gtk_label_set_text(GTK_LABEL(ctx->pinyin_label), "拼音: ");
            update_candidate_buttons(ctx);
        } else {
            // 英文模式下插入空格
            add_to_buffer(ctx, " ");
        }
    } else if (strcmp(label, "中/英") == 0) {
        // 切换输入模式
        ctx->mode = (ctx->mode == MODE_ENGLISH) ? MODE_CHINESE : MODE_ENGLISH;
        ctx->pinyin_buffer[0] = '\0';
        ctx->pinyin_len = 0;
        ctx->candidate_count = 0;
        gtk_label_set_text(GTK_LABEL(ctx->pinyin_label), 
                         ctx->mode == MODE_CHINESE ? "拼音: " : "英文模式");
        update_candidate_buttons(ctx);
        update_mode_button(ctx);
    } else if (strcmp(label, "?123") == 0) {
        // 从字母布局切换到数字布局
        ctx->layout = LAYOUT_NUMBERS;
        update_layout_button(ctx);
        update_keyboard_layout(ctx);
    } else if (strcmp(label, "ABC") == 0) {
        // 从数字/符号布局返回字母布局
        ctx->layout = LAYOUT_LETTERS;
        update_layout_button(ctx);
        update_keyboard_layout(ctx);
    } else if (strcmp(label, "#+=") == 0) {
        // 从数字布局切换到符号布局
        ctx->layout = LAYOUT_SYMBOLS;
        update_layout_button(ctx);
        update_keyboard_layout(ctx);
    } else if (strcmp(label, "123") == 0) {
        // 从符号布局返回数字布局
        ctx->layout = LAYOUT_NUMBERS;
        update_layout_button(ctx);
        update_keyboard_layout(ctx);
    }    else if (strcmp(label, "◀") == 0) {
        // 上一页
        if (ctx->current_page > 0) {
            ctx->current_page--;
            update_candidate_buttons(ctx);
        }
    } else if (strcmp(label, "▶") == 0) {
        // 下一页
        if (ctx->current_page < ctx->total_pages - 1) {
            ctx->current_page++;
            update_candidate_buttons(ctx);
        }
    } else if (strcmp(label, "⏎") == 0) {
        // 处理回车键
        if (ctx->mode == MODE_CHINESE && ctx->candidate_count > 0) {
            // 中文模式下选择第一个候选词
            add_to_buffer(ctx, ctx->candidates[0]);
            ctx->pinyin_buffer[0] = '\0';
            ctx->pinyin_len = 0;
            ctx->candidate_count = 0;
            gtk_label_set_text(GTK_LABEL(ctx->pinyin_label), "拼音: ");
            update_candidate_buttons(ctx);
        }
        // 添加换行符
        add_to_buffer(ctx, "\n");
    } else if (strlen(label) == 1 && isalpha(label[0])) {
        // 处理字母键
        if (ctx->mode == MODE_CHINESE) {
            // 中文模式下输入拼音
            if (ctx->pinyin_len < MAX_PINYIN_LEN - 1) {
                ctx->pinyin_buffer[ctx->pinyin_len++] = tolower(label[0]);
                ctx->pinyin_buffer[ctx->pinyin_len] = '\0';
                find_candidates(ctx);
            }
        } else {
            // 英文模式下直接输入字母
            char str[2] = {label[0], '\0'};
            add_to_buffer(ctx, str);
        }
    } else {
        // 其他字符直接输入
        add_to_buffer(ctx, label);
    }
}

// 窗口点击事件处理
static gboolean on_window_click(GtkWidget *widget, GdkEventButton *event, gpointer data) {
    InputContext *ctx = (InputContext *)data;
    gint x, y;
    gtk_widget_translate_coordinates(ctx->entry, widget, event->x, event->y, &x, &y);
    
    GtkAllocation alloc;
    gtk_widget_get_allocation(ctx->entry, &alloc);
    
    if (x >= 0 && x < alloc.width && y >= 0 && y < alloc.height) {
        gtk_widget_show_all(ctx->keyboard_window);
    } else {
        gtk_widget_hide(ctx->keyboard_window);
    }
    return FALSE;
}

// 输入框获取焦点回调
static void on_entry_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer data) {
    InputContext *ctx = (InputContext *)data;
    gtk_widget_show_all(ctx->keyboard_window);
}

// 更新键盘布局函数
void update_keyboard_layout(InputContext *ctx) {
    // 清除当前键盘布局
    GList *children, *iter;
    children = gtk_container_get_children(GTK_CONTAINER(ctx->keyboard_container));
    for(iter = children; iter != NULL; iter = g_list_next(iter)) {
        gtk_widget_destroy(GTK_WIDGET(iter->data));
    }
    g_list_free(children);

    // 加载CSS样式 - 更现代化的设计
    GtkCssProvider *provider = gtk_css_provider_new();
    gtk_css_provider_load_from_data(provider, 
        "button { "
        "   font-size: 20px; " // 增大字体
        "   min-height: 56px; " // 增大按键高度
        "   min-width: 56px; " // 设置最小宽度
        "   border-radius: 8px; " // 增大圆角
        "   margin: 3px; " // 增加间距
        "   padding: 8px; " // 增加内边距
        "   border: none; "
        "   background: #f8f9fa; "
        "   color: #202124; "
        "   box-shadow: 0 2px 4px rgba(0,0,0,0.1); " // 增强阴影效果
        "} "
        "button:hover { "
        "   background: #e8eaed; "
        "} "
        "button:active { "
        "   background: #dadce0; "
        "   box-shadow: none; "
        "} "
        // 特殊按键样式
        ".special-button { "
        "   min-width: 70px; " // 增大特殊按键宽度
        "   background: #e8eaed; "
        "   font-weight: bold; "
        "} "
        ".mode-button { "
        "   font-weight: bold; "
        "   background: #1a73e8; "
        "   color: white; "
        "} "
        ".active-mode { "
        "   background: #1a73e8; "
        "   color: white; "
        "} "
        // 空格键样式
        ".space-button { "
        "   min-width: 200px; " // 增大空格键宽度
        "   background: #f1f3f4; "
        "} "
        // 修改键盘容器样式
        ".keyboard-container { "
        "   background: #f1f3f4; "
        "   padding: 10px; " // 增加内边距
        "   border-radius: 12px; "
        "   box-shadow: 0 4px 8px rgba(0,0,0,0.1); "
        "} "
        ".candidate-button { "
        "   font-size: 14px; "
        "   min-height: 40px; "
        "   background: #e6f4ea; "
        "   color: #137333; "
        "} "
        ".pinyin-label { "
        "   font-size: 14px; "
        "   color: #5f6368; "
        "   margin-bottom: 4px; "
        "} "
        ".page-control { "
        "   background: #f1f3f4; "
        "   border-radius: 4px; "
        "   padding: 2px; "
        "} "
        ".page-button { "
        "   min-height: 32px; "
        "   min-width: 32px; "
        "   padding: 0; "
        "   background: #e8eaed; "
        "} "
        ".page-label { "
        "   font-size: 13px; "
        "   color: #5f6368; "
        "} "
        ".row-container { "
        "   margin: 0; "
        "   padding: 0; "
        "} "
        , -1, NULL);

    GtkStyleContext *context = gtk_widget_get_style_context(ctx->keyboard_container);
    gtk_style_context_add_class(context, "keyboard-container");
    gtk_style_context_add_provider(context, GTK_STYLE_PROVIDER(provider), 
                                 GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
    g_object_unref(provider);

    // 根据当前布局创建新的键盘
    switch (ctx->layout) {
        case LAYOUT_LETTERS: {
            // 第一行 - 数字行
            GtkWidget *row1 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_style_context_add_class(gtk_widget_get_style_context(row1), "row-container");
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row1, TRUE, TRUE, 0);
            
            // 数字行按键
            const char *row1_keys[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "←"};
            for (int i = 0; i < 11; i++) {
                GtkWidget *button = gtk_button_new_with_label(row1_keys[i]);
                if (strcmp(row1_keys[i], "←") == 0) {
                    GtkStyleContext *btn_ctx = gtk_widget_get_style_context(button);
                    gtk_style_context_add_class(btn_ctx, "special-button");
                }
                g_signal_connect(button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
                gtk_box_pack_start(GTK_BOX(row1), button, TRUE, TRUE, 0);
            }
            
            // 第二行 - QWERTY行
            GtkWidget *row2 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_style_context_add_class(gtk_widget_get_style_context(row2), "row-container");
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row2, TRUE, TRUE, 0);
            
            const char *row2_keys[] = {"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"};
            for (int i = 0; i < 10; i++) {
                GtkWidget *button = gtk_button_new_with_label(row2_keys[i]);
                g_signal_connect(button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
                gtk_box_pack_start(GTK_BOX(row2), button, TRUE, TRUE, 0);
            }
            
            // 第三行 - ASDF行（稍微缩进以模拟标准键盘布局）
            GtkWidget *row3 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_style_context_add_class(gtk_widget_get_style_context(row3), "row-container");
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row3, TRUE, TRUE, 0);
            
            const char *row3_keys[] = {"a", "s", "d", "f", "g", "h", "j", "k", "l"};
            for (int i = 0; i < 9; i++) {
                GtkWidget *button = gtk_button_new_with_label(row3_keys[i]);
                g_signal_connect(button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
                gtk_box_pack_start(GTK_BOX(row3), button, TRUE, TRUE, 0);
            }

            // 第四行 - ZXCV行
            GtkWidget *row4 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_style_context_add_class(gtk_widget_get_style_context(row4), "row-container");
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row4, TRUE, TRUE, 0);
            
            // 添加Shift键
            GtkWidget *shift_btn = gtk_button_new_with_label("⇧");
            GtkStyleContext *shift_ctx = gtk_widget_get_style_context(shift_btn);
            gtk_style_context_add_class(shift_ctx, "special-button");
            g_signal_connect(shift_btn, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row4), shift_btn, FALSE, FALSE, 0);
            gtk_widget_set_size_request(shift_btn, 50, -1);
            
            const char *row4_keys[] = {"z", "x", "c", "v", "b", "n", "m", ",", "."};
            for (int i = 0; i < 9; i++) {
                GtkWidget *button = gtk_button_new_with_label(row4_keys[i]);
                g_signal_connect(button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
                gtk_box_pack_start(GTK_BOX(row4), button, TRUE, TRUE, 0);
            }
            
            // 第五行 - 功能键行（字母布局）
            GtkWidget *row5 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_style_context_add_class(gtk_widget_get_style_context(row5), "row-container");
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row5, TRUE, TRUE, 0);

            // 中英文切换按钮
            ctx->mode_button = gtk_button_new_with_label("中/英");
            GtkStyleContext *mode_ctx = gtk_widget_get_style_context(ctx->mode_button);
            gtk_style_context_add_class(mode_ctx, "mode-button");
            if (ctx->mode == MODE_CHINESE) {
                gtk_style_context_add_class(mode_ctx, "active-mode");
            }
            g_signal_connect(ctx->mode_button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), ctx->mode_button, FALSE, FALSE, 0);
            gtk_widget_set_size_request(ctx->mode_button, 60, -1);

            // 符号键 - 在字母布局中显示"?123"
            GtkWidget *symbol_btn = gtk_button_new_with_label("?123");
            GtkStyleContext *symbol_ctx = gtk_widget_get_style_context(symbol_btn);
            gtk_style_context_add_class(symbol_ctx, "special-button");
            g_signal_connect(symbol_btn, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), symbol_btn, FALSE, FALSE, 0);
            gtk_widget_set_size_request(symbol_btn, 60, -1);

            // 空格键
            GtkWidget *space_btn = gtk_button_new_with_label("空格");
            GtkStyleContext *space_ctx = gtk_widget_get_style_context(space_btn);
            gtk_style_context_add_class(space_ctx, "space-button");
            g_signal_connect(space_btn, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), space_btn, TRUE, TRUE, 0);

            // 布局切换按钮 - 在字母布局中不需要显示
            ctx->layout_button = gtk_button_new_with_label("ABC");
            update_layout_button(ctx);
            GtkStyleContext *layout_ctx = gtk_widget_get_style_context(ctx->layout_button);
            gtk_style_context_add_class(layout_ctx, "special-button");
            g_signal_connect(ctx->layout_button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), ctx->layout_button, FALSE, FALSE, 0);
            gtk_widget_set_size_request(ctx->layout_button, 60, -1);

            // 回车键
            GtkWidget *enter_btn = gtk_button_new_with_label("⏎");
            GtkStyleContext *enter_ctx = gtk_widget_get_style_context(enter_btn);
            gtk_style_context_add_class(enter_ctx, "special-button");
            g_signal_connect(enter_btn, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), enter_btn, FALSE, FALSE, 0);
            gtk_widget_set_size_request(enter_btn, 60, -1);

            // 调整行间距
            gtk_box_set_spacing(GTK_BOX(row1), 6); // 增加到6像素
            gtk_box_set_spacing(GTK_BOX(row2), 6);
            gtk_box_set_spacing(GTK_BOX(row3), 6);
            gtk_box_set_spacing(GTK_BOX(row4), 6);
            gtk_box_set_spacing(GTK_BOX(row5), 6);

            // 调整特殊按键的尺寸
            gtk_widget_set_size_request(shift_btn, 80, -1);
            gtk_widget_set_size_request(space_btn, 250, -1); // 增大空格键
            gtk_widget_set_size_request(enter_btn, 80, -1); // 增大回车键
            break;
        }
            
        case LAYOUT_NUMBERS: {
            // 第一行 - 数字行
            GtkWidget *row1 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row1, TRUE, TRUE, 0);
            
            const char *row1_keys[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "←"};
            for (int i = 0; i < 11; i++) {
                GtkWidget *button = gtk_button_new_with_label(row1_keys[i]);
                if (strcmp(row1_keys[i], "←") == 0) {
                    GtkStyleContext *btn_ctx = gtk_widget_get_style_context(button);
                    gtk_style_context_add_class(btn_ctx, "special-button");
                }
                g_signal_connect(button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
                gtk_box_pack_start(GTK_BOX(row1), button, TRUE, TRUE, 0);
            }
            
            // 第二行 - 符号行1
            GtkWidget *row2 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row2, TRUE, TRUE, 0);
            
            const char *row2_keys[] = {"-", "/", ":", ";", "(", ")", "$", "&", "@", "\""};
            for (int i = 0; i < 10; i++) {
                GtkWidget *button = gtk_button_new_with_label(row2_keys[i]);
                g_signal_connect(button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
                gtk_box_pack_start(GTK_BOX(row2), button, TRUE, TRUE, 0);
            }
            
            // 第三行 - 符号行2
            GtkWidget *row3 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row3, TRUE, TRUE, 0);
            
            const char *row3_keys[] = {".", ",", "?", "!", "'", "_", "+", "=", "*"};
            for (int i = 0; i < 9; i++) {
                GtkWidget *button = gtk_button_new_with_label(row3_keys[i]);
                g_signal_connect(button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
                gtk_box_pack_start(GTK_BOX(row3), button, TRUE, TRUE, 0);
            }
            
            // 第四行 - 符号行3
            GtkWidget *row4 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row4, TRUE, TRUE, 0);
            
            GtkWidget *more_btn = gtk_button_new_with_label("#+=");
            GtkStyleContext *more_ctx = gtk_widget_get_style_context(more_btn);
            gtk_style_context_add_class(more_ctx, "special-button");
            g_signal_connect(more_btn, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row4), more_btn, FALSE, FALSE, 0);
            gtk_widget_set_size_request(more_btn, 60, -1);
            
            const char *row4_keys[] = {"[", "]", "{", "}", "#", "%", "^", "\\", "|"};
            for (int i = 0; i < 9; i++) {
                GtkWidget *button = gtk_button_new_with_label(row4_keys[i]);
                g_signal_connect(button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
                gtk_box_pack_start(GTK_BOX(row4), button, TRUE, TRUE, 0);
            }
            
            // 第五行 - 功能键行
            GtkWidget *row5 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row5, TRUE, TRUE, 0);
            
            // 中英文切换按钮
            ctx->mode_button = gtk_button_new_with_label("中/英");
            GtkStyleContext *mode_ctx = gtk_widget_get_style_context(ctx->mode_button);
            gtk_style_context_add_class(mode_ctx, "mode-button");
            if (ctx->mode == MODE_CHINESE) {
                gtk_style_context_add_class(mode_ctx, "active-mode");
            }
            g_signal_connect(ctx->mode_button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), ctx->mode_button, FALSE, FALSE, 0);
            gtk_widget_set_size_request(ctx->mode_button, 60, -1);
            
            // 空格键
            GtkWidget *space_btn = gtk_button_new_with_label("空格");
            GtkStyleContext *space_ctx = gtk_widget_get_style_context(space_btn);
            gtk_style_context_add_class(space_ctx, "space-button");
            g_signal_connect(space_btn, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), space_btn, TRUE, TRUE, 0);
            
            // 布局切换按钮
            ctx->layout_button = gtk_button_new_with_label("123");
            update_layout_button(ctx);
            GtkStyleContext *layout_ctx = gtk_widget_get_style_context(ctx->layout_button);
            gtk_style_context_add_class(layout_ctx, "special-button");
            g_signal_connect(ctx->layout_button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), ctx->layout_button, FALSE, FALSE, 0);
            gtk_widget_set_size_request(ctx->layout_button, 60, -1);
            
            // 回车键
            GtkWidget *enter_btn = gtk_button_new_with_label("⏎");
            GtkStyleContext *enter_ctx = gtk_widget_get_style_context(enter_btn);
            gtk_style_context_add_class(enter_ctx, "special-button");
            g_signal_connect(enter_btn, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), enter_btn, FALSE, FALSE, 0);
            gtk_widget_set_size_request(enter_btn, 60, -1);

            // 调整行间距
            gtk_box_set_spacing(GTK_BOX(row1), 6); // 增加到6像素
            gtk_box_set_spacing(GTK_BOX(row2), 6);
            gtk_box_set_spacing(GTK_BOX(row3), 6);
            gtk_box_set_spacing(GTK_BOX(row4), 6);
            gtk_box_set_spacing(GTK_BOX(row5), 6);

            // 调整特殊按键的尺寸
            gtk_widget_set_size_request(space_btn, 250, -1); // 增大空格键
            gtk_widget_set_size_request(enter_btn, 80, -1); // 增大回车键
            break;
        }
            
        case LAYOUT_SYMBOLS: {
            // 第一行 - 特殊符号行1
            GtkWidget *row1 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row1, TRUE, TRUE, 0);
            
            const char *row1_keys[] = {"~", "`", "•", "√", "π", "÷", "×", "¶", "∆", "£", "←"};
            for (int i = 0; i < 11; i++) {
                GtkWidget *button = gtk_button_new_with_label(row1_keys[i]);
                if (strcmp(row1_keys[i], "←") == 0) {
                    GtkStyleContext *btn_ctx = gtk_widget_get_style_context(button);
                    gtk_style_context_add_class(btn_ctx, "special-button");
                }
                g_signal_connect(button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
                gtk_box_pack_start(GTK_BOX(row1), button, TRUE, TRUE, 0);
            }
            
            // 第二行 - 特殊符号行2
            GtkWidget *row2 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row2, TRUE, TRUE, 0);
            
            const char *row2_keys[] = {"€", "¥", "©", "®", "™", "✓", "§", "¢", "°", "•"};
            for (int i = 0; i < 10; i++) {
                GtkWidget *button = gtk_button_new_with_label(row2_keys[i]);
                g_signal_connect(button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
                gtk_box_pack_start(GTK_BOX(row2), button, TRUE, TRUE, 0);
            }
            
            // 第三行 - 特殊符号行3
            GtkWidget *row3 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row3, TRUE, TRUE, 0);
            
            const char *row3_keys[] = {"«", "»", "≤", "≥", "≠", "≈", "∞", "µ", "Ω"};
            for (int i = 0; i < 9; i++) {
                GtkWidget *button = gtk_button_new_with_label(row3_keys[i]);
                g_signal_connect(button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
                gtk_box_pack_start(GTK_BOX(row3), button, TRUE, TRUE, 0);
            }
            
            // 第四行 - 特殊符号行4
            GtkWidget *row4 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row4, TRUE, TRUE, 0);
            
            GtkWidget *more_btn = gtk_button_new_with_label("123");
            GtkStyleContext *more_ctx = gtk_widget_get_style_context(more_btn);
            gtk_style_context_add_class(more_ctx, "special-button");
            g_signal_connect(more_btn, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row4), more_btn, FALSE, FALSE, 0);
            gtk_widget_set_size_request(more_btn, 60, -1);
            
            const char *row4_keys[] = {"¡", "¿", "†", "‡", "★", "♠", "♣", "♥", "♦"};
            for (int i = 0; i < 9; i++) {
                GtkWidget *button = gtk_button_new_with_label(row4_keys[i]);
                g_signal_connect(button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
                gtk_box_pack_start(GTK_BOX(row4), button, TRUE, TRUE, 0);
            }
            
            // 第五行 - 功能键行
            GtkWidget *row5 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
            gtk_box_pack_start(GTK_BOX(ctx->keyboard_container), row5, TRUE, TRUE, 0);
            
            // 中英文切换按钮
            ctx->mode_button = gtk_button_new_with_label("中/英");
            GtkStyleContext *mode_ctx = gtk_widget_get_style_context(ctx->mode_button);
            gtk_style_context_add_class(mode_ctx, "mode-button");
            if (ctx->mode == MODE_CHINESE) {
                gtk_style_context_add_class(mode_ctx, "active-mode");
            }
            g_signal_connect(ctx->mode_button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), ctx->mode_button, FALSE, FALSE, 0);
            gtk_widget_set_size_request(ctx->mode_button, 60, -1);
            
            // 空格键
            GtkWidget *space_btn = gtk_button_new_with_label("空格");
            GtkStyleContext *space_ctx = gtk_widget_get_style_context(space_btn);
            gtk_style_context_add_class(space_ctx, "space-button");
            g_signal_connect(space_btn, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), space_btn, TRUE, TRUE, 0);
            
            // 布局切换按钮
            ctx->layout_button = gtk_button_new_with_label("#+=");
            update_layout_button(ctx);
            GtkStyleContext *layout_ctx = gtk_widget_get_style_context(ctx->layout_button);
            gtk_style_context_add_class(layout_ctx, "special-button");
            g_signal_connect(ctx->layout_button, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), ctx->layout_button, FALSE, FALSE, 0);
            gtk_widget_set_size_request(ctx->layout_button, 60, -1);
            
            // 回车键
            GtkWidget *enter_btn = gtk_button_new_with_label("⏎");
            GtkStyleContext *enter_ctx = gtk_widget_get_style_context(enter_btn);
            gtk_style_context_add_class(enter_ctx, "special-button");
            g_signal_connect(enter_btn, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
            gtk_box_pack_start(GTK_BOX(row5), enter_btn, FALSE, FALSE, 0);
            gtk_widget_set_size_request(enter_btn, 60, -1);

            // 调整行间距
            gtk_box_set_spacing(GTK_BOX(row1), 6); // 增加到6像素
            gtk_box_set_spacing(GTK_BOX(row2), 6);
            gtk_box_set_spacing(GTK_BOX(row3), 6);
            gtk_box_set_spacing(GTK_BOX(row4), 6);
            gtk_box_set_spacing(GTK_BOX(row5), 6);

            // 调整特殊按键的尺寸
            gtk_widget_set_size_request(space_btn, 250, -1); // 增大空格键
            gtk_widget_set_size_request(enter_btn, 80, -1); // 增大回车键
            break;
        }
    }

    // 增大模式切换按钮
    gtk_widget_set_size_request(ctx->mode_button, 80, -1);
    // 设置键盘容器的边距
    gtk_container_set_border_width(GTK_CONTAINER(ctx->keyboard_container), 10);
    // 显示所有键盘元素
    gtk_widget_show_all(ctx->keyboard_container);
}

// 创建键盘窗口函数
void create_keyboard_window(InputContext *ctx) {
    ctx->keyboard_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(ctx->keyboard_window), "拼音输入法");
    gtk_window_set_default_size(GTK_WINDOW(ctx->keyboard_window), 1024, 480); // 更宽但更紧凑的高度
    gtk_container_set_border_width(GTK_CONTAINER(ctx->keyboard_window), 8);
    gtk_window_set_type_hint(GTK_WINDOW(ctx->keyboard_window), GDK_WINDOW_TYPE_HINT_UTILITY);
    gtk_window_set_decorated(GTK_WINDOW(ctx->keyboard_window), FALSE);
    gtk_window_set_position(GTK_WINDOW(ctx->keyboard_window), GTK_WIN_POS_CENTER);
    
    // 主容器
    GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
    gtk_container_add(GTK_CONTAINER(ctx->keyboard_window), vbox);
    
    // 顶部区域 - 包含拼音显示和候选词
    GtkWidget *top_area = gtk_box_new(GTK_ORIENTATION_VERTICAL, 4);
    gtk_box_pack_start(GTK_BOX(vbox), top_area, FALSE, FALSE, 0);
    
    // 拼音显示区域 - 水平布局包含拼音标签和页码控制
    GtkWidget *pinyin_area = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 4);
    gtk_box_pack_start(GTK_BOX(top_area), pinyin_area, FALSE, FALSE, 0);
    
    // 拼音显示标签
    ctx->pinyin_label = gtk_label_new("拼音: ");
    GtkStyleContext *label_style = gtk_widget_get_style_context(ctx->pinyin_label);
    gtk_style_context_add_class(label_style, "pinyin-label");
    gtk_widget_set_halign(ctx->pinyin_label, GTK_ALIGN_START);
    gtk_box_pack_start(GTK_BOX(pinyin_area), ctx->pinyin_label, TRUE, TRUE, 0);
    
    // 页码控制区域
    GtkWidget *page_control = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
    gtk_style_context_add_class(gtk_widget_get_style_context(page_control), "page-control");
    gtk_box_pack_end(GTK_BOX(pinyin_area), page_control, FALSE, FALSE, 0);
    
    // 上一页按钮
    GtkWidget *prev_page = gtk_button_new_with_label("◀");
    gtk_style_context_add_class(gtk_widget_get_style_context(prev_page), "page-button");
    g_signal_connect(prev_page, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
    gtk_box_pack_start(GTK_BOX(page_control), prev_page, FALSE, FALSE, 0);
    
    // 页码标签
    ctx->page_label = gtk_label_new("第1/1页");
    gtk_style_context_add_class(gtk_widget_get_style_context(ctx->page_label), "page-label");
    gtk_box_pack_start(GTK_BOX(page_control), ctx->page_label, FALSE, FALSE, 4);
    
    // 下一页按钮
    GtkWidget *next_page = gtk_button_new_with_label("▶");
    gtk_style_context_add_class(gtk_widget_get_style_context(next_page), "page-button");
    g_signal_connect(next_page, "clicked", G_CALLBACK(on_keyboard_button_clicked), ctx);
    gtk_box_pack_start(GTK_BOX(page_control), next_page, FALSE, FALSE, 0);
    
    // 候选词区域 - 使用流式布局
    ctx->candidate_box = gtk_flow_box_new();
    gtk_flow_box_set_selection_mode(GTK_FLOW_BOX(ctx->candidate_box), GTK_SELECTION_NONE);
    gtk_flow_box_set_homogeneous(GTK_FLOW_BOX(ctx->candidate_box), TRUE); // 设置为TRUE保证每个按钮大小一致
    gtk_flow_box_set_row_spacing(GTK_FLOW_BOX(ctx->candidate_box), 4);
    gtk_flow_box_set_column_spacing(GTK_FLOW_BOX(ctx->candidate_box), 4);
    gtk_flow_box_set_max_children_per_line(GTK_FLOW_BOX(ctx->candidate_box), 10); // 每行最多显示10个
    gtk_flow_box_set_activate_on_single_click(GTK_FLOW_BOX(ctx->candidate_box), TRUE); // 单击激活候选词
    gtk_box_pack_start(GTK_BOX(top_area), ctx->candidate_box, FALSE, FALSE, 0);
    
    for (int i = 0; i < CANDIDATES_PER_PAGE; i++) {
        ctx->candidate_buttons[i] = gtk_button_new_with_label("");
        gtk_widget_hide(ctx->candidate_buttons[i]);
        g_object_set_data(G_OBJECT(ctx->candidate_buttons[i]), "index", GINT_TO_POINTER(i));
        g_signal_connect(ctx->candidate_buttons[i], "clicked", G_CALLBACK(on_candidate_selected), ctx);
        
        // 候选词按钮样式
        GtkStyleContext *button_style = gtk_widget_get_style_context(ctx->candidate_buttons[i]);
        gtk_style_context_add_class(button_style, "candidate-button");
        
        // 设置候选词按钮的最大宽度
        gtk_widget_set_size_request(ctx->candidate_buttons[i], 30, 30); // 例如，设置最大宽度为40像素
        gtk_flow_box_insert(GTK_FLOW_BOX(ctx->candidate_box), ctx->candidate_buttons[i], -1);
    }
    
    // 分隔线
    GtkWidget *separator = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
    gtk_box_pack_start(GTK_BOX(vbox), separator, FALSE, FALSE, 2);
    
    // 键盘容器
    ctx->keyboard_container = gtk_box_new(GTK_ORIENTATION_VERTICAL, 4);
    gtk_box_pack_start(GTK_BOX(vbox), ctx->keyboard_container, TRUE, TRUE, 0);
    
    // 初始化键盘布局
    update_keyboard_layout(ctx);
    
    gtk_widget_hide(ctx->keyboard_window);
}

// 创建主窗口
void create_main_window(InputContext *ctx) {
    ctx->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(ctx->window), "GTK拼音输入法");
    gtk_window_set_default_size(GTK_WINDOW(ctx->window), 500, 200);
    gtk_window_set_position(GTK_WINDOW(ctx->window), GTK_WIN_POS_CENTER);
    gtk_container_set_border_width(GTK_CONTAINER(ctx->window), 16);
    
    // 应用现代风格
    GtkCssProvider *provider = gtk_css_provider_new();
    gtk_css_provider_load_from_data(provider, 
        ".main-window { "
        "   background-color: #ffffff; "
        "} "
        ".input-field { "
        "   font-size: 16px; "
        "   padding: 10px; "
        "   border-radius: 8px; "
        "   border: 1px solid #dadce0; "
        "} "
        ".info-label { "
        "   font-size: 14px; "
        "   color: #5f6368; "
        "   margin-top: 8px; "
        "} ", -1, NULL);
    
    GtkStyleContext *window_style = gtk_widget_get_style_context(ctx->window);
    gtk_style_context_add_class(window_style, "main-window");
    gtk_style_context_add_provider(window_style, GTK_STYLE_PROVIDER(provider), 
                                 GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
    
    GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 12);
    gtk_container_add(GTK_CONTAINER(ctx->window), vbox);
    
    // 标题标签
    GtkWidget *title = gtk_label_new("GTK拼音输入法演示");
    PangoAttrList *attrs = pango_attr_list_new();
    pango_attr_list_insert(attrs, pango_attr_weight_new(PANGO_WEIGHT_BOLD));
    pango_attr_list_insert(attrs, pango_attr_scale_new(1.2));
    gtk_label_set_attributes(GTK_LABEL(title), attrs);
    pango_attr_list_unref(attrs);
    gtk_widget_set_margin_bottom(title, 8);
    gtk_box_pack_start(GTK_BOX(vbox), title, FALSE, FALSE, 0);
    
    // 输入框
    ctx->entry = gtk_entry_new();
    GtkStyleContext *entry_style = gtk_widget_get_style_context(ctx->entry);
    gtk_style_context_add_class(entry_style, "input-field");
    gtk_box_pack_start(GTK_BOX(vbox), ctx->entry, FALSE, FALSE, 0);
    g_signal_connect(ctx->entry, "focus-in-event", G_CALLBACK(on_entry_focus_in), ctx);
    
    // 说明标签 - 修复引号和特殊字符问题
    GtkWidget *label = gtk_label_new("点击输入框将弹出拼音输入法键盘\n"
                                    "• 点击\"中/英\"按钮切换中英文输入模式\n"
                                    "• 点击\"ABC\"、\"123\"或\"\\#+=\"按钮切换键盘布局");
    gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT);
    gtk_widget_set_halign(label, GTK_ALIGN_START);
    GtkStyleContext *label_style = gtk_widget_get_style_context(label);
    gtk_style_context_add_class(label_style, "info-label");
    gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
    
    g_signal_connect(ctx->window, "button-press-event", G_CALLBACK(on_window_click), ctx);
    create_keyboard_window(ctx);
    
    g_object_unref(provider);
}
